package com.xiaoluo.web.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Project : Monitor
 * Package : com.xiaoluo.web.interceptor
 * Created by Willian.
 * Date  : 2015/9/22 13:24.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final String XRW = "X-Requested-With";
    private static final String AJAX_REQ = "XMLHttpRequest";
    //

    private static final String[] IGNORE_URI = {"/login.jsp", "/login","/dologin","/upload","/getPods","/project/callback","/resources"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = false;
        String url = request.getRequestURL().toString();

        for (String s : IGNORE_URI) {
            if (url.contains(s)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            Object obj = request.getSession().getAttribute("SESSION_USER");
            if(obj != null ){
                flag = true;
            }else{
                String xrw = request.getHeader(XRW);
                if(xrw != null && AJAX_REQ.equals(xrw)){
                    response.getWriter().write("{\"code\":302,\"msg\":\"session timeout.\"}");
                    response.getWriter().flush();
                }else {
                    response.sendRedirect(request.getContextPath()+"/login");
                }
                flag = false;
            }

        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
